<?php

namespace App\Http\Controllers\Payment;

use App\Common\Result;
use App\Http\Controllers\Controller;
use App\Models\Inquiry\InquirySheet;
use App\Service\Balance\BalanceService;
use App\Service\Customer\CustomerOauthService;
use App\Service\Customer\CustomerService;
use App\Service\Easemob\EasemobService;
use App\Service\Goods\GoodsService;
use App\Service\Indent\OrderService;
use App\Service\Payment\AlipayService;
use App\Service\Payment\WeixinService;
use App\Service\ServiceLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use DB;
use App\Service\Jpush\JpushService;
use App\Service\Work\BestWorksService;
use App\Service\Work\WorksRelateService;

class PaymentController extends Controller
{
    public function unifiedOrder(Request $request)
    {
        Result::isEmpty($request->uid,'无有效用户信息',-16);
        Result::isEmpty($request->order_id,'无效订单',-23);

        $channel = $request->channel;


        if(!$order_info = OrderService::getOrder($request->order_id)){
            Result::msg('-23','error','无效订单');
        }

        if($order_info['price'] <=0){
            Result::msg('-23','error','无效订单');
        }

        if($channel == ''){
            Result::msg('-23','error','无效订单');
        }

        if(!$user_info = CustomerOauthService::findUser(['uid'=>$request->uid])){
            Result::msg('-24','error','无效用户');
        }

        $orderArr = array(
            'uid' => $request->uid,
            'order_id' => $order_info['order_id'],
            'price' => $order_info['price'],
            'channel' => $channel,
            'open_id' => $user_info->openid
        );

        $inquiry = InquirySheet::where('id',$order_info->inquiry_sheet_id)->first();
        switch ($channel) {
            case 'weixin':
                $result = WeixinService::unifiedOrder($orderArr);
                if($result)
                    Result::msg('0','success',['sign'=>$result,'order'=>$order_info,'inquiry' => $inquiry,'time' =>date('Y-m-d H:i:s',time())]);
                else
                    Result::msg('-22','error','订单失败');
                break;
            case 'alipay':
                $result = AlipayService::unifiedOrder($orderArr);
                if($result){
                    Result::msg('0','success',['sign'=>$result]);
                }else{
                    Result::msg('-22','error','订单失败');
                }
                break;
            default:
                Result::msg('-22','error','订单失败');
        }

    }

    /**
     * 零钱支付
     * @param Request $request
     */
    public function walletOrder(Request $request)
    {
        Result::isEmpty($request->uid,'无有效用户信息',-16);
        Result::isEmpty($request->order_id,'无效订单',-23);

        if(!$order_info = OrderService::getOrder($request->order_id)){
            Result::msg('-23','error','无效订单');
        }

        if($request->uid != $order_info['uid']){
            Result::msg('-23','error','无效订单');
        }

        DB::beginTransaction();

        $user_balance = OrderService::selectUserBalanceLock($order_info['uid']);
        if($user_balance<$order_info['price']){
            Result::msg('-35','error','余额不足');
        }



        try{
            $sql_result = 1;
            $status = 0;
            $buy_message = '';
            if($order_info['order_type'] == 1){
                //资源付费
                $status = 1;  //已发货
                $buy_message = '若收到的商品没有任何问题，您的确认收货是对卖家最大的鼓励。';
            }

            if($order_info['order_type'] == 2){
                //商品付费
                $status = 0; //未发货
                $buy_message = '卖家将尽快发货,请注意查收!';
            }

            $data = array(
                'paystatus' => 1,
                'source_order_id' => '',
                'status' => $status,
                'payways' => 2, //余额支付
                'updated_at' => date("Y-m-d H:i:s",time()),
            );

            $buy_info = array(
                'uid' => $order_info['uid'],
                'relation_uid' =>  $order_info['auid'],
                'order_id' => $order_info['order_id'],
                'money' => -$order_info['price'],
                'title' => '零钱支付',
                'trade_no' => '',
                'type' => 1,
                'article_id' => $order_info['article_id'],
                'created_at' => date('Y-m-d H:i:s'),
            );

            $detail_data = array(
                'order_id' => $order_info['order_id'],
                'remark' => 2, //买家购买商品
                'order_type'=> $order_info['order_type'],
                'created_at' => date("Y-m-d H:i:s")
            );


            //更新订单
            OrderService::changeOrder($order_info['order_id'], $data);
            //插入交易记录
            BalanceService::addBalanceLog($buy_info);
            //插入订单明细
            OrderService::addOrderDetail($detail_data);
            //商品购买量增加
            WorksRelateService::addWorksBuyNum($order_info['article_id']);
            //减去余额
            CustomerService::changeUser($order_info['uid'],['balance'=>($user_balance-$order_info['price'])]);
            DB::commit();
        } catch (\Exception $e){
            //失败
            $sql_result = 0;
            ServiceLog::record("error.txt",$request->order_id." : ".$e->getMessage(),"error");
            DB::rollback();
        }

        //发送买卖消息
        $ext = Controller::getSendExt('sj_00000000000005');
        if($sql_result){
            $user_info =  CustomerService::findUser(['uid'=>$order_info['uid']]);
            $message = "{$user_info['nickname']}"."购买了你的商品";
            $article_info = BestWorksService::findArticle([
                'id' => $order_info['article_id']
            ]);
            $ext['article_id'] = $order_info['article_id'];
            $ext['title'] = $article_info['title'];
            $ext['push_class'] = 'pay';
            $ext['content'] = $message;
            $easembo = new EasemobService();
            $easembo->sendText('sj_00000000000005',$order_info['auid'],$message,$ext);
            $easembo->sendText('sj_00000000000005',$order_info['uid'],$buy_message,$ext);
            JpushService::pushMessage($order_info['auid'],$message,$ext);
            JpushService::pushMessage($order_info['uid'],$buy_message,$ext);
        }else{
            //失败消息
            $easembo = new EasemobService();
            $easembo->sendText('sj_00000000000005',$order_info['uid'],'订单失败请联系客服');
            JpushService::pushMessage($order_info['uid'],'订单失败请联系客服');
        }
        Result::msg('0','success',[]);
    }

    /**
     * 支付宝回调
     * @param Request $request
     */
    public function alipayNotify(Request $request)
    {
	    $params = $request->all();
	  
        if(isset($params['trade_status']) && $params['trade_status'] == 'TRADE_SUCCESS'){
            if(!AlipayService::getSignVerify($params, $params['sign'])){
                  $string = date("Y-m-d H:i:s")."/".$params['sign']."/"."faild";
                  ServiceLog::record("error.txt",$string,"error"); 
                  goto Ready;
             }

            $order_id = $params['out_trade_no'];
            //订单存在
            if( !$order_info = OrderService::getOrderArray([
                'order_id' => $order_id,
                'status' => 0
            ]) ){
                goto Ready;
            }

            DB::beginTransaction();

            try{
                $status = 1;
                $data = array(
                    'source_order_id' => $params['trade_no'],
                    'status' => $status,
                    'payways' => 1,
                    'updated_at' => date("Y-m-d H:i:s",time()),
                );

                $detail_data = array(
                    'order_id' => $order_id,
                    'remark' => 2, //买家购买商品
                    'order_type'=> $order_info['order_type'],
                    'created_at' => date("Y-m-d H:i:s")
                );
                //更新订单
                OrderService::changeOrder($order_id, $data);
                //插入订单明细
                OrderService::addOrderDetail($detail_data);

                DB::commit();
            } catch (\Exception $e){
                //失败
                ServiceLog::record("error.txt",$order_id." : ".$e->getMessage(),"error");
                DB::rollback();
            }
        }

        Ready:

        echo "success";     
    }

    /**
     * 微信回调
     * @param Request $request
     */
    public function weixinNotify(Request $request)
    {
        $paramstr = @file_get_contents('php://input');

        $params = WeiXinService::xmlToArray($paramstr);
        $wx_config = config('payment.weixin');
        $sign = WeixinService::generateSign($params,$wx_config['key']);

        $return = array(
            'return_code' => 'SUCCESS',
            'return_msg' => 'OK'
        );

        //返回参数检验
        if($params['result_code'] != 'SUCCESS' || !array_key_exists('sign', $params)){
            $return['return_code'] = "FAIL";
            $return['return_msg'] = "签名不存在";
        }

        if($sign == $params['sign']){

            $order_id = $params['out_trade_no'];

            //订单存在
            if(!$order_info = OrderService::getOrderArray([
                'order_id' => $order_id,
                'status' => 0
            ])){
                goto Ready;
            }

            DB::beginTransaction();

            try{
                $data = array(
                    'status' => 1,
                    'source_order_id' => $params['transaction_id'],
                    'updated_at' => date("Y-m-d H:i:s",time()),
                    'payways' => 0,
                    'pay_method' => 'online'
                );

                $detail_data = array(
                    'order_id' => $order_id,
                    'remark' => '购买商品付款', //买家购买商品
                    'status' => 1,
                    'created_at' => date("Y-m-d H:i:s")
                );

                //更新订单
                OrderService::changeOrder($order_id, $data);

                //插入订单明细
                OrderService::addOrderDetail($detail_data);


                DB::commit();
            } catch (\Exception $e){
                //失败
                ServiceLog::record("error.txt",$order_id." : ".$e->getMessage(),"error");
                DB::rollback();
            }
        }

        Ready:

        echo "success";
    }
}
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        